#include "accelerometer.h"
#include "display.h"
#include "error.h"
#include "h01.h"
#include "iic.h"
#include "reports.h"
#include "rtc.h"
#include "usb.h"
#include "vx.h"

uint	timeOfs;
uint	timer;
uint	curSteps;
uint	systick;
ushort	error;
ushort	flags;
ushort	ordBase=0x8800;
ubyte	status;
ubyte	clrSteps;
REPORTS reports={RPT_VERSION,0,
	RPT_TICKLO,0,	RPT_TICKHI,0,
	RPT_OFFSETLO,0,	RPT_OFFSETHI,0,
	RPT_VOLTB,0,	RPT_VOLTC,0,	RPT_VOLTS,3300,	
	RPT_TKCHGL,0,	RPT_TKCHGH,0,
	RPT_TCCHGC,0,	RPT_TCCHGV,0,
	RPT_STEPSLO,0,	RPT_STEPSHI,0,
	0,0,			0,0,
};
SAVE	savRam;
Jump*	bootVect=(Jump*)0x08000000;
Jump*	tagetBas=(Jump*)0x08008800;

static void testAccelerometer(void){
	initAccelerometer();
	ubyte v;
	readIIC(ADD_ACC,REG_WHOIAM,&v,1);
	waitIIC();
	if(v!=0x33)
		error|=ERROR_ACCSENSOR;
}
static void testH01(void){
	init(RCC_SYSCLK_Div512);
	if(SystemCoreClock!=48000000)
		error |=ERROR_SYSCLK;
	watchdogOn();
	if(usbNoPower())
		PWR_EnterSTANDBYMode();
	RCC_HCLKConfig(RCC_SYSCLK_Div2);
}
static void testRTC(void){
	initRTC();
	for(timer=0;timer<10000;){
		if(RCC_GetFlagStatus(RCC_FLAG_LSERDY))
			return;
		outBar(timer/700+3);
	}
	error |= ERROR_RTC;
}

//------------------------------------------------------------------------------

void initVecTable(void){
	NVIC_SetVectorTable(NVIC_VectTab_FLASH,0);
}
void main(void){
	testH01();
	displayOn();
	outBar(1);
	usbOn();
	outBar(2);
	testAccelerometer();
	outBar(3);
	testRTC();
	outBar(19);
	while(1){
		if(error)
			outHex(error);
		else if(usbNoPower())
			PWR_EnterSTANDBYMode();
		else{
			report();
			dispatch();
		}
		__WFI();
	}
}